﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SocketClient
{
    public partial class Form1 : Form
    {
        delegate void ControlChangeHandler(string msg1, string msg2);

        int port;
        IPAddress address;
        private Socket mySocket;

        public Form1()
        {
            InitializeComponent();
        }

        private void StartConnection()
        {
            port = Convert.ToInt32(this.txtPort.Text.Trim());
            address = IPAddress.Parse(this.txtAddress.Text.Trim());
            try
            {
                mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                mySocket.Connect(address, port);
                //mySocket.Connect(new IPEndPoint(address,port ));
                string msg = "联机至远程Socket.........";
                this.Invoke(new ControlChangeHandler(this.onChange), new object[] { msg, "" });
            }
            catch (SocketException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Send()
        {
            byte[] data = new byte[1024];
            int length;
            try
            {
                data = Encoding.ASCII.GetBytes(this.txtSend.Text.Trim());
                length = mySocket.Send(data);
                string msg = "传送了" + length.ToString() + "字节的数据";
                this.Invoke(new ControlChangeHandler(this.onChange), new object[] { msg, "" });
            }
            catch (SocketException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void onChange(string msg1, string msg2)
        {
            if (msg1 != "")
            {
                this.txtConnection.Text += msg1 + "\r\n";
            }
            if (msg2 != "")
            {
                this.txtSend.Text += msg2 + "\r\n";
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(new ThreadStart(this.StartConnection));
            th.IsBackground = true;
            th.Start();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(new ThreadStart(this.Send));
            th.IsBackground = true;
            th.Start();
        }
    }
}
